# -*- coding: utf-8 -*-
from DB import DB
import uuid

class CC:

    '''
         Control and Config
    '''

    def __init__(self, userid):
        # config
        self.useDefaultConfig()

        # control
        self.UserId = userid
        self.TaskId = ''
        self.Keyword = ''
        self.Price = 1
        self.Stopped = True
        self.Quit = False

    def useDefaultConfig(self):
        self.MaxProducts = 1000
        self.SiteAlibaba = True
        self.SiteAmazon = True
        self.SiteDangdang = True
        self.SiteJD = True
        self.SiteTmall = True
        self.SiteTaobao = True
        self.Debug = True

    def quit(self):
        self.Quit = True

    def isQuitted(self):
        return self.Quit

    def getConfigBoolValue(self, row, field_no):
        if row[field_no] == None:
            return True

        if row[field_no]:
            return True

        return False

    def loadConfig(self):
        db = DB()
        row = db.Fetch('SELECT MaxProducts, SiteAlibaba, SiteAmazon, SiteDangdang, SiteJD, SiteTmall, SiteTaobao, Debug FROM ClientFunc WHERE UserId = %s', (self.UserId,))
        db.Close()

        if not row:
            self.useDefaultConfig()
            return 

        self.MaxProducts = row[0]
        self.SiteAlibaba = self.getConfigBoolValue(row, 1)
        self.SiteAmazon = self.getConfigBoolValue(row, 2)
        self.SiteDangdang = self.getConfigBoolValue(row, 3)
        self.SiteJD = self.getConfigBoolValue(row, 4)
        self.SiteTmall = self.getConfigBoolValue(row, 5)
        self.SiteTaobao = self.getConfigBoolValue(row, 6)
        self.Debug = self.getConfigBoolValue(row, 7)

    def start(self, keyword, price):
        self.Stopped = False
        self.Quit = False
        self.TaskId = str(uuid.uuid1())
        self.Price = price
        self.Keyword = keyword

        self.incTaskCount()

        self.loadConfig()

    def stop(self):
        self.Stopped = True

    def isStopped(self):
        return self.Stopped

    def getTaskId(self):
        return self.TaskId

    def getTaskCount(self):
        db = DB()
        row = db.Fetch('SELECT TaskCount FROM TaskStat WHERE UserId = %s', (self.UserId,))
        db.Close()

        if not row:
            return 0

        return row[0]

    def incTaskCount(self):
        db = DB()
        row = db.Fetch('SELECT TaskCount FROM TaskStat WHERE UserId = %s', (self.UserId,))
        if row:
            db.Execute('UPDATE TaskStat SET TaskCount = TaskCount + 1 WHERE UserId = %s', (self.UserId,))
        else:
            db.Execute('INSERT INTO TaskStat VALUES(%s, %s)', (self.UserId, 0))
        db.Commit()
        db.Close()

    def getInfo(self):
        status = ''
        if self.Stopped:
            status = 'stopped'
        else:
            status = 'running'

        task_count = self.getTaskCount()
        return self.TaskId, self.Keyword, self.Price, status, task_count
